#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020-05-18 15:08:55
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.6.5
# 功能     ： 卸料及激活制样

# 制样机状态表
DEVICE_TABLE = "T_550_RT_ST"
# 卸料主表
UNLOAD_MAIN_TABLE = "T_540_UNLOAD_MASTE"
# 卸料子表
UNLOAD_SUB_TABLE = "T_540_UNLOAD_DETAILONE"
# 制样票主表
TICKET_MAIN_TABLE = "T_550_ZYCZP_MASTE"
# 数据有效时间,只查询24小时内的数据
DAY = 1


class TaskMain(object):
    """docstring for main"""

    def __init__(self):
        super(TaskMain, self).__init__()
        self.log = main.log
        self.cics = main.conn.get("CICS") if not isinstance(dict,type(main.conn.get("CICS")))else main.conn.get("CICS").get('connect')
        self.ics = main.conn.get("ICS") if not isinstance(dict,type(main.conn.get("ICS")))else main.conn.get("ICS").get('connect')
        self.sdk = main.sdk


    # 查询采样结束的自动票
    def get_cy_ticket_end(self):
        sql = ("SELECT a.GID PGID,b.* FROM T_RL_CZPMAIN a LEFT JOIN T_RL_CZPMAIN b ON a.CYBH=b.CYBH WHERE "
               "a.CZPLX='00000002' AND a.CZPZT<'00000005' AND a.CZPZXMS=1 AND "
               "b.CZPZT IN ('00000005','00000007') AND b.CZPZXMS=1 AND b.KPSJ>(SYSDATE-3) AND "
               "b.CZPLX IN ('00000001','00000006','00000007') ")
        self.log.debug("查询自动制样未完成,采样自动完成的票:{}".format(sql))
        return self.cics.loadSql(sql, True)

    # 查询卸料主表
    def get_unload_main(self, gid = None):
        if gid:
            sql = "SELECT * FROM {} WHERE F_ID ='{}'".format(UNLOAD_MAIN_TABLE, gid)
            self.log.debug("查询是否存卸料主表:{}".format(sql))
            return self.ics.loadSql(sql, True)
        else:
            sql = "SELECT * FROM {} WHERE F_KPSJ>(SYSDATE-{}) AND F_CZPZT!='00000005'".format(UNLOAD_MAIN_TABLE, DAY)
            self.log.debug("查询卸料主表:{}".format(sql))
            return self.ics.loadSql(sql, True)

    # 插入卸料合样主表
    def insert_unload_main(self, data):
        sql = "DELETE FROM {} WHERE F_ID='{PGID}'".format(UNLOAD_MAIN_TABLE, **data)
        result = self.ics.execSql(sql)
        self.log.info("清除可能存在的主表:{},结果:{}".format(sql, result))

        sql = ("INSERT INTO {}(F_ID,F_CZPZT,F_KPSJ,F_CYBM,F_USER,F_SYN_FLAG) "
               "VALUES ('{PGID}','0001',SYSDATE,'{CYBH}','ICS',0)").format(UNLOAD_MAIN_TABLE, **data)
        self.log.info("下发卸料合样主表:{}".format(sql))
        return self.ics.execSql(sql)

    def get_unload_sub(self, pgid):
        sql = "SELECT * FROM T_RL_HYYTCZPZB WHERE CZPGID ='{}' AND ZHUANGTAI='0001' AND ISREADICS=0".format(pgid)
        self.log.debug("查询是否存卸料子表:{}".format(sql))
        return self.cics.loadSql(sql, True)

    # 插入卸料合样子表
    def insert_unload_sub(self, data):
        sql = "DELETE FROM {} WHERE F_GID=:1".format(UNLOAD_SUB_TABLE)
        values = [[row['GID'], ] for row in data]
        result = self.ics.execSql(sql, values)
        self.log.info("清除可能存在的子表:{},结果:{}".format(sql, result))

        sql = ("INSERT INTO {} (F_GID,F_PID,F_SYTH,F_TYBM,F_FYBM,F_ZHUANGTAI,F_SYN_FLAG) VALUES "
               "(:1,:2,:3,:4,:5,:6,'0')").format(UNLOAD_SUB_TABLE)
        values = [[row['GID'], row['CZPGID'], row['SYTH'], row['TYBM'], row['FYBM'], row['ZHUANGTAI']] for row in data]
        self.log.info("下发卸料合样子表:{},值:{}".format(sql, values))
        return self.ics.execSql(sql, values)

    # 更新卸料合样子表下发标记
    def update_unload_sub(self, pgid):
        sql = "UPDATE T_RL_HYYTCZPZB SET ISREADICS=1 WHERE CZPGID='{}' AND ZHUANGTAI='0001'".format(pgid)
        self.log.info("更新卸料合样子表下发标记:{}".format(sql))
        return self.cics.execSql(sql, True)

    # 查询中间库主表
    def get_ticket_main(self, status = "00000003"):
        sql = "SELECT * FROM {} WHERE F_CZPZT='{}' AND F_KPSJ>(SYSDATE-{}) ORDER BY F_CZPBH".format(TICKET_MAIN_TABLE,
                                                                                                    status, DAY)
        self.log.debug("查询主表：".format(sql))
        return self.ics.loadSql(sql, True)

    # 激活操作票
    def activate_ticket(self, row):
        sql = "UPDATE {} SET F_CZPZT = '00000003' WHERE F_ID = '{F_ID}' ".format(TICKET_MAIN_TABLE, **row)
        self.log.info("激活制样票命令：{}".format(sql))
        result = self.ics.execSql(sql)
        if result:
            self.log.info("激活制样票,采样码:{F_CYBM},等待制样机制样......".format(**row))
            return result

    # 下发合样主子表
    def unload_ticket_down(self):
        data = self.get_cy_ticket_end()
        if not data:
            self.log.debug("没有需要筛选卸料的操作票")
            return
        # 下发合样卸料主子表
        for i, row in enumerate(data):
            pgid = row.get('PGID')
            # 下发卸料合样子表
            unoad_sub_data = self.get_unload_sub(pgid)
            if unoad_sub_data:
                result = self.insert_unload_sub(unoad_sub_data)
                if result:
                    self.update_unload_sub(pgid)

            # 下发卸料合样主表
            unload_main_data = self.get_unload_main(pgid)
            if not unload_main_data:
                self.insert_unload_main(row)

    # 下发卸料指令
    def send_unload_command(self, status, command, row):
        # 空闲及未申请卸料,下发卸料
        if status == 1 and command == 0:
            sql = "UPDATE {} SET F_RES0 = 1".format(DEVICE_TABLE)
            self.log.info("向制样机申请卸料：{}".format(sql))
            result = self.ics.execSql(sql)
            return

        # 等待中。。。。
        if status != 5 and command == 1:
            self.log.info("已在申请卸料中，等待制样样同意卸料。。。。。。")
            return

        # 下发指令
        if status == 5 and (not command or command == 0):

            sql = "UPDATE {} SET F_CZPZT='0003',F_SYN_FLAG=0 WHERE F_ID='{F_ID}' AND F_CYBM='{F_CYBM}'".format(
                    UNLOAD_MAIN_TABLE, **row)
            result = self.ics.execSql(sql)
            if result:
                self.log.info("采样码：{F_CYBM},卸料指令已发送成功，等待卸料。。。".format(**row))

    # 查询制样机状态
    def get_device_status(self):
        sql = "SELECT * FROM {} ".format(DEVICE_TABLE)
        data = self.ics.loadSql(sql, True)
        if data:
            return data[0].get('F_V'), data[0].get('F_RES0')
        else:
            return None, None

    # 更新激活处理标记
    def update_unload_main(self, gid):
        sql = "UPDATE {} SET F_CZPZT='00000005' WHERE F_ID='{}'".format(UNLOAD_MAIN_TABLE, gid)
        self.log.info("更新激活处理标记：{}".format(sql))
        self.ics.execSql(sql)

    def run(self):
        # 下发合样主子表
        self.unload_ticket_down()

        # 检测制样机状态
        device_status, unload_command = self.get_device_status()
        self.log.info(
                "制样机状态：{},（1空闲，2运行，5允许卸料）,卸料命令:{},（1,申请卸料，0或空为复位）".format(device_status, unload_command)
                )

        # 制样中
        data = self.get_ticket_main()
        if data:
            self.log.info(
                    ("制样机正在制样中...票：{F_CZPBH},执行模式：{F_CZPZXMS},(1自动,2人工,3半自动 )，"
                     "采样码：{F_CYBH},等待制样结束或挂起").format(**data[0])
                    )
            return

        # 查询卸料合样主表
        unload_main_data = self.get_unload_main()
        if unload_main_data:
            self.log.info("待合样，卸料的采样码：{}".format([row['F_CYBM'] for row in unload_main_data]))

        # 检测卸料中的票
        if unload_main_data and [row for row in unload_main_data if row['F_CZPZT'] == '0003']:
            self.log.info("存在卸料中的票，等待卸料完成。。。。")
            return

        # 检测合样完成的票
        if unload_main_data and [row for row in unload_main_data if row['F_CZPZT'] == '0002']:
            # 取一条
            value = [row for row in unload_main_data if row['F_CZPZT'] == '0002'][0]
            # self.log.info("存在合样完成的票，下发申请卸料。。。")
            # 下发
            self.send_unload_command(device_status, unload_command, value)
            return

        # 检测卸料完成的票
        if unload_main_data and [row for row in unload_main_data if row['F_CZPZT'] == '0004']:
            # 取一张票激活
            value = [row for row in unload_main_data if row['F_CZPZT'] == '0004'][0]
            result = self.activate_ticket(value)
            if not result:
                self.log.warning("激活制样操作票,采样码:{F_CYBM},失败...".format(**value))
                return
            self.update_unload_main(value['F_ID'])


info = {}
app = TaskMain()
app.run()